package top.lyjwn.todo.common.utils;

import com.alibaba.fastjson2.JSONObject;

//import javax.persistence.Column;
//import javax.persistence.Entity;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class EntityUtil {

/*
    public static  <T>  T mapToHibernateEntity(Map<String,Object> map, Class<T> clazz)
    {
        Entity entity = clazz.getAnnotation(Entity.class);
        if (entity!=null)
        {
            Object t = null;
            try {
                t = clazz.forName(clazz.getName()).getDeclaredConstructor().newInstance();
            } catch (InstantiationException |IllegalAccessException | InvocationTargetException|NoSuchMethodException|ClassNotFoundException  e) {
                e.printStackTrace();
            }
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if (declaredField.getAnnotation(Column.class)!=null) {
                    Object o = map.get(declaredField.getAnnotation(Column.class).name());
                    String jsonString = JSONObject.toJSONString(o);
                    Object o1 = JSONObject.parseObject(jsonString, declaredField.getType());
                    setFieldValueByName(declaredField.getName(),t,o1);
                }
            }
            return (T)t;
        }
        return  null;
    }
*/
    public static void setFieldValueByName(String fieldName, Object object, Object setObj) {
        // 此处应该判断beanObj,property不为null
        try {
            PropertyDescriptor pd = new PropertyDescriptor(fieldName, object.getClass());
            Method setMethod = pd.getWriteMethod();
            setMethod.invoke(object, setObj);
        } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
